#include "client.h"
#include <QtNetwork>
#include "define.h"

CClient::CClient()
{
    m_payloadSize=64*1024;
    m_totalBytes=0;
    m_bytesWritten=0;
    m_bytesToWrite=0;
    m_tcpClient=new QTcpSocket(this);
    connect(m_tcpClient,SIGNAL(connected()),this,SLOT(connected()));
    connect(m_tcpClient,SIGNAL(bytesWritten(qint64)),this,SLOT(updateClientProgress(qint64)));
    connect(m_tcpClient,SIGNAL(error(QAbstractSocket::SocketError)),this,SLOT(displayError(QAbstractSocket::SocketError)));

}
 
void CClient::send(){
    m_bytesWritten=0;
    emit sigCliStatus(CLI_MSG_INF, QStringLiteral("connecting %1:%2...").arg(m_ipAddress).arg(m_port));
    m_tcpClient->connectToHost(m_ipAddress,m_port);
}
 
void CClient::startTransfer(){
    
    QString fileName = m_fileNames[m_file_idx];
    m_localFile=new QFile(fileName);
    if(!m_localFile->open(QFile::ReadOnly)){
        qDebug()<<"client open file error!";
        emit sigCliStatus(CLI_MSG_ERR, QString("client open file %1 error!").arg(fileName));
        transferNext();
        return;
    }
    
    m_totalBytes=m_localFile->size();
    QDataStream sendOut(&m_outBlock,QIODevice::WriteOnly);
    sendOut.setVersion(QDataStream::Qt_5_7);
    QString currentFileName=fileName.right(fileName.size()-fileName.lastIndexOf('/')-1);
    sendOut<<qint64(0)<<qint64(0)<<currentFileName;
    m_totalBytes+=m_outBlock.size();
    sendOut.device()->seek(0);
    sendOut<<m_totalBytes<<qint64(m_outBlock.size()-sizeof(qint64)*2);
    m_bytesToWrite=m_totalBytes-m_tcpClient->write(m_outBlock);
    emit sigCliStatus(CLI_MSG_INF, QString("begin to send file %1(%2)").arg(fileName).arg(m_totalBytes));
    m_outBlock.resize(0);
}
 
void CClient::updateClientProgress(qint64 numBytes){
    m_bytesWritten+=(int)numBytes;
    if(m_bytesToWrite>0){
        m_outBlock=m_localFile->read(qMin(m_bytesToWrite,m_payloadSize));
        m_bytesToWrite-=(int)m_tcpClient->write(m_outBlock);
        m_outBlock.resize(0);
    }
    else{
        m_localFile->close();
    }
//    ui->clientProgressBar->setMaximum(m_totalBytes);
//    ui->clientProgressBar->setValue(m_bytesWritten);

    if(m_bytesWritten==m_totalBytes){
        emit sigCliStatus(CLI_MSG_INF, QStringLiteral("trans file %1 succesful!").arg(m_fileNames[m_file_idx]));
        emit sigCliStatus(CLI_SND_OVER, QStringLiteral("%1").arg(m_file_idx));
        m_localFile->close();
       
        transferNext();
    }
}
 
void CClient::displayError(QAbstractSocket::SocketError){
    qDebug()<<m_tcpClient->errorString();
    emit sigCliStatus(CLI_MSG_ERR,m_tcpClient->errorString());
    m_tcpClient->close();
}
  
CClient::~CClient()
{

}

void CClient::run()
{
    send();
}

void CClient::send(QString ipAddress, int port, QStringList filenames)
{
    if (filenames.size() <= 0) {
        emit sigCliStatus(CLI_MSG_ERR, QString("filelist is empty"));
        return;
    }
    m_ipAddress = ipAddress;
    m_port = port;
    m_fileNames = filenames;
    m_file_idx = 0;
    this->send();
}

void CClient::connected() {
    emit sigCliStatus(CLI_MSG_INF, QStringLiteral("connected"));

    startTransfer();
}

void CClient::transferNext(){
    
    m_totalBytes=0;
    m_bytesWritten=0;
    m_bytesToWrite=0;
    m_file_idx++;
    
    if (m_file_idx >= m_fileNames.size()) {
         emit sigCliStatus(CLI_SND_ALL, "files in the list are all sended!");
         m_tcpClient->close();
         return;
    }
    else{
        startTransfer();
    }
}

